// 引入接口文件
import { addFun,editFun,queryInfo,findProduct,getPranentAtt} from './areaListDetailServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
import { rstr2b64 } from '../../../../utils/md5'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'

// 初始默认状态
const defultState = {
  modelObj: {
    btnLoading: false,
  },
  tableObj: {
    key: '',
    defaultValue: '',
    itemContent: '',
    itemContent1: ''
  },
  tableData:[],
  areaList: [],
  loading: false,
  keys: 0,
  actionType: 'add',
  query: {
    id: '',
    tableName: '',//表单名称
    attributeName: '', //字段名称
    tableType: '2',//表格类型 1代表集团 2代表区域 3代表项目
    sort: '', //排序
    isShow: '', //是否必填
    isRadio: '', //控件类型 1代表单选 2代表多选 3文本框 4 segment框 5 日期控件 6 富文本框 7 媒体类型 8 固定值 9 多选+输入框
    tableTab: '', //所属页签
    isEnable: '1',//0代表禁用 1代表启用
    systemType: '',//systemType区分系统项自定义项
    itemContent: '',//内容
    defaultValue: '',//默认值
    areaId: '',
    areaName: ''
  },
  systemNameList: [],//系统项
  systemData: {},//系统项
}

// 声明module
const tmpModule = {
  namespace: 'defaultModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          // 执行业务操作
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          if(query.actionType == 'check'|| query.actionType == 'edit'){
            dispatch({type: 'queryInfo',payload: {id:query.id}})
          }
          dispatch({type: 'findProduct',payload: {}})
          dispatch({type: 'getPranentAtt',payload: {}})
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    *findProduct({payload},{put,select,call}){
      let {areaList} = yield select(state => state[tmpModule.namespace])
      let params = {
        type: 2,
      }
      const { success, msg, result } = yield call(findProduct, {...params})
      if(success){
        let list = result
        if(!list.length){
          return
        }
        areaList =  list.map((item,index)=>{
          return {
            label: item.areaName,
            value: item.areaId,
          }
        })
        yield put({type: 'updateStore', payload: {areaList}})
      }
    },
    *getPranentAtt({payload},{put,select,call}){
        let {systemNameList,systemData} = yield select(state => state[tmpModule.namespace])
        let params = {}
        const { success, msg, result } = yield call(getPranentAtt, {...params})
        if(success){
          let list = result
          systemData = result
          if(!list.length){
            return
          }
          systemNameList =  list.map((item,index)=>{
            return {
              label: item.attributeName,
              value: item.id,
            }
          })
          yield put({type: 'updateStore', payload: {systemNameList,systemData}})
        }
      },
      // 查询记录
      *queryInfo({payload}, {put, select, call}){
          let {query,tableData} = yield select(state => state[tmpModule.namespace])
          let params = { 
            id: payload.id,
            tableType: 2
          }

          const { success,result} = yield call(queryInfo, {...params})
          if(success){
            query = result.attributeGroup?result.attributeGroup:''
            let itemContent = result&&result.attributeGroup.itemContent?result.attributeGroup.itemContent:''
            let name = result&&result.attributeGroup.defaultValue?result.attributeGroup.defaultValue:''
            if(result.attributeGroup.isRadio == 7){
              let arr2 = []
              let itemContentObj = JSON.parse(itemContent)
              for (let i in itemContentObj) {
                  let o = {
                    key: i,
                    defaultValue: 0,
                    itemContent1: itemContentObj[i],
                    itemContent: i
                  };
                  if(i == name){
                    o.defaultValue = 1;
                  }
                  arr2.push(o)
              }
              tableData = arr2
            }else{
              let list =  itemContent.split(",")
              let arr = []
              for(var item of list){
                let obj ={
                  key:'a'+item,
                  defaultValue: 0,
                  itemContent: item,
                }
                if(item == name){
                  obj.defaultValue = 1
                }
                arr.push(obj)
              }
              tableData = arr
            }
            yield put({
              type: 'updateStore',
              payload: {query,tableData}
            })
          }
      },
      *submit({payload},{put,select,call}){
        let {actionType,query,tableData} = yield select(state => state[tmpModule.namespace])
        if(query.isRadio == 1 ||query.isRadio == 2 ||query.isRadio == 8){
          let list = []
          for(var item of tableData){
            list.push(item.itemContent)
            if(item.defaultValue == 1){
              query.defaultValue = item.itemContent
            }
          }
          query.itemContent =  list.join(",")
        }
        if(query.isRadio == 7){
          let obj2 = {}
          tableData.forEach(item => {
              obj2[item.itemContent] = item.itemContent1
          })
          for(var item of tableData){
            if(item.defaultValue == 1){
              query.defaultValue = item.itemContent
            }
          }
          query.itemContent =  JSON.stringify(obj2)
        }
        let params = query
        if(actionType == 'add'){
          let { success, msg, data } = yield call(addFun, {...params})
          if(success){
            message.success('提交成功')
            hashHistory.push({
              pathname: '/home/predictManage/areaList',
              query: {}
            })
          }
        }
        if(actionType == 'edit'){
          let { success, msg, data } = yield call(editFun, {...params})
          if(success){
            message.success('提交成功')
            hashHistory.push({
              pathname: '/home/predictManage/areaList',
              query: {}
            })
          }
        }
      }
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
